import React from 'react';
import styles from './style';
import {
    TouchableWithoutFeedback,
    SafeAreaView,
    View,
    DeviceEventEmitter,
    TouchableOpacity,
    Text,
    Image,
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Hot from '../hot/pages/hot';
import Mine from '../mine/pages/mine';
import Find from '../find/pages/find';
import { getUserInfo } from '../../common/api/user';
import AsyncStorage from '@react-native-async-storage/async-storage';

const eye = require('./img/eye.png');
const eyeLine = require('./img/eye_line.png');
const camera = require('./img/camera.png');
const cameraLine = require('./img/camera_line.png');

export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tabs: [
                {
                    id: 0,
                    select: true,
                    icon: cameraLine,
                    selectIcon: camera,
                    style: styles.tabIcon,
                    selectStyle: styles.tabIcon,
                },
                {
                    id: 1,
                    select: false,
                    icon: {
                        uri: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2F50%2Fv2-16898564e0a7dfb0eb1f2072dae62f3f_hd.jpg&refer=http%3A%2F%2Fpic4.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613130485&t=9adfc5111d4292e9d98bad6d928eaa0f',
                    },
                    selectIcon: {
                        uri: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2F50%2Fv2-16898564e0a7dfb0eb1f2072dae62f3f_hd.jpg&refer=http%3A%2F%2Fpic4.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613130485&t=9adfc5111d4292e9d98bad6d928eaa0f',
                    },
                    style: styles.avatar,
                    selectStyle: styles.avatarSelect,
                },
                {
                    id: 2,
                    select: false,
                    icon: eyeLine,
                    selectIcon: eye,
                    style: styles.tabIconEye,
                    selectStyle: styles.tabIconEye,
                },
            ],
            page: <Hot navigation={this.props.navigation} />,
            grayScreen: false,
        };
    }
    async componentDidMount() {
        // 这里的`param`可以为空，接受你B页面传过来的数据
        this.subscription = DeviceEventEmitter.addListener('ChangeUserAvatar', param => {
            // 刷新头像等
            this.getData();
        });
        console.log('componentDidMount1');
        const userInfo = await AsyncStorage.getItem('userInfo');
        if (userInfo) {
            const avatar = JSON.parse(userInfo).avatar;
            if (avatar) {
                return this.setAvatar(avatar);
            }
        }
        this.getData();
    }
    componentWillUnmount() {
        this.subscription.remove();
    }
    getData = async () => {
        const res = await getUserInfo();
        if (!res || !res.avatar) {
            return;
        }
        this.setAvatar(res.avatar);
        // const img1 = this.image1;
        // console.log((img1.props.source.uri = res.avatar));
    };
    setAvatar = avatar => {
        setTimeout(() => {
            this.setState({
                tabs: this.state.tabs.map(it => {
                    if (it.id === 1) {
                        // 坑： Image不能直接设置uri
                        it.icon = { uri: avatar };
                        it.selectIcon = { uri: avatar };
                    }
                    return it;
                }),
            });
        }, 50);
    };
    tabSelectAction(index) {
        let grayScreen = index === 1 ? true : false;
        let { navigation } = this.props;
        let tabs = this.state.tabs;
        tabs.forEach((item, i) => {
            item.select = index === i ? true : false;
        });
        let contentPage =
            index === 0 ? (
                <Hot navigation={navigation} />
            ) : index === 1 ? (
                <Mine navigation={navigation} />
            ) : (
                <Find navigation={navigation} />
            );
        this.setState({
            tabs: [...tabs],
            page: contentPage,
            grayScreen,
        });
        if (index === 1) {
            this[`image${index}`].rotate();
        } else {
            this[`image${index}`].jello(1200);
        }
    }
    handleImageRef(ref, index) {
        this[`image${index}`] = ref;
    }

    render() {
        let { tabs, page, grayScreen } = this.state;
        return (
            <View
                style={[
                    styles.screenContainer,
                    { backgroundColor: grayScreen ? 'rgb(242, 242, 242)' : '#fff' },
                ]}
            >
                <SafeAreaView style={styles.container}>
                    <View style={styles.content}>{page}</View>
                    <View style={styles.tabsContainer}>
                        <View style={styles.tabs}>
                            {tabs.map((item, index) => (
                                <TouchableWithoutFeedback
                                    key={item.id}
                                    onPress={() => this.tabSelectAction(index)}
                                >
                                    <Animatable.Image
                                        ref={ref => this.handleImageRef(ref, index)}
                                        style={item.select ? item.selectStyle : item.style}
                                        source={item.select ? item.selectIcon : item.icon}
                                    />
                                </TouchableWithoutFeedback>
                            ))}
                        </View>
                    </View>
                </SafeAreaView>
            </View>
        );
    }
}
